// Follow.js - 用户关注模型
const { sequelize } = require('../config/db');
const { DataTypes } = require('sequelize');

/**
 * 用户关注模型
 * 管理用户之间的关注关系
 */
class Follow {
  constructor() {
    // 定义关注表模型
    this.model = sequelize.define('user_follow', {
      follower_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        comment: '关注者ID',
        primaryKey: true
      },
      followed_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        comment: '被关注者ID',
        primaryKey: true
      },
      created_at: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW
      }
    }, {
      tableName: 'user_follow',
      timestamps: true,
      createdAt: 'created_at',
      updatedAt: false,
      // 移除索引定义，因为使用复合主键
      indexes: []
    });
  }

  /**
   * 检查是否已关注
   * @param {number} followerId - 关注者ID
   * @param {number} followedId - 被关注者ID
   * @returns {Promise<boolean>} 是否已关注
   */
  async checkFollow(followerId, followedId) {
    try {
      const result = await this.model.findOne({
        where: {
          follower_id: followerId,
          followed_id: followedId
        }
      });
      return !!result;
    } catch (error) {
      console.error('检查关注状态失败:', error);
      throw error;
    }
  }

  /**
   * 关注用户
   * @param {number} followerId - 关注者ID
   * @param {number} followedId - 被关注者ID
   * @returns {Promise<object>} 创建的关注记录
   */
  async create(followerId, followedId) {
    try {
      // 不允许关注自己
      if (followerId === followedId) {
        throw new Error('不能关注自己');
      }

      // 检查是否已经关注
      const isFollowing = await this.checkFollow(followerId, followedId);
      if (isFollowing) {
        throw new Error('已经关注该用户');
      }

      // 创建关注记录
      const result = await this.model.create({
        follower_id: followerId,
        followed_id: followedId
      });

      return result;
    } catch (error) {
      console.error('关注用户失败:', error);
      throw error;
    }
  }

  /**
   * 取消关注
   * @param {number} followerId - 关注者ID
   * @param {number} followedId - 被关注者ID
   * @returns {Promise<number>} 删除的记录数
   */
  async destroy(followerId, followedId) {
    try {
      const result = await this.model.destroy({
        where: {
          follower_id: followerId,
          followed_id: followedId
        }
      });
      return result;
    } catch (error) {
      console.error('取消关注失败:', error);
      throw error;
    }
  }

  /**
   * 获取粉丝数量
   * @param {number} userId - 用户ID
   * @returns {Promise<number>} 粉丝数量
   */
  async getFanCount(userId) {
    try {
      const count = await this.model.count({
        where: {
          followed_id: userId
        }
      });
      return count;
    } catch (error) {
      console.error('获取粉丝数量失败:', error);
      throw error;
    }
  }

  /**
   * 获取关注数量
   * @param {number} userId - 用户ID
   * @returns {Promise<number>} 关注数量
   */
  async getFollowingCount(userId) {
    try {
      const count = await this.model.count({
        where: {
          follower_id: userId
        }
      });
      return count;
    } catch (error) {
      console.error('获取关注数量失败:', error);
      throw error;
    }
  }
}

module.exports = new Follow();